package com.example.yichuangyun.mvvm.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityAddressBookBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.dialog.SortPopupWindow;
import com.example.yichuangyun.dialog.TreeDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.model.contacts.AddressDataModel;
import com.example.yichuangyun.model.contacts.ContactsParamsModel;
import com.example.yichuangyun.model.contacts.ContactsTagModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.view.AddressBookViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.AddressBookAdapter;
import com.example.yichuangyun.mvvm.ui.adapter.TagAdapter;
import com.example.yichuangyun.ui.adapter.LabelAdapter;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.treelist.Node;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 通讯录
 */
public class AddressBookActivity extends BaseActivity<ActivityAddressBookBinding, AddressBookViewModel> implements View.OnClickListener, LabelAdapter.OnLabelItemClickListener, TagAdapter.OnTagItemClickListener {

    /**
     * 跟进状态/联系人来源/标签名称
     */
    private LabelAdapter contactsTypeAdapter, followStatusAdapter, contactsFromAdapter;
    private TagAdapter tagAdapter;
    private List<ContactsTagModel> tagsData = new ArrayList<>();
    private final List<String> tagStrData = new ArrayList<>();
    private List<LabelModel> contactsFromData = new ArrayList<>();
    private List<AddressDataModel.AddressModel> data = new ArrayList<>();
    private AddressBookAdapter addressBookAdapter;
    private Integer followStatus, contactsFrom, contactsType = 1;
    private TreeDialog treeDialog;
    private final List<Node> mData = new ArrayList<>();
    private boolean isFirstRequest = true;
    private String orgId;

    private SortPopupWindow popupWindow;
    private String sortType = "", orderKey = "";
    private int page = 1;
    private String contactsTypeName = "我的联系人";

    /**
     * 拨打的电话号码
     */
    private String mTelNumber;
    private String contactId;
    private String clientName;
    private MyDialog myDialog;
    private Node chooseNode;
    private String mKeyword;

    @Override
    protected AddressBookViewModel bindModel() {
        return getViewModel(this, AddressBookViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void initData() {
        binding.includeTop.tvTitleText.setText(getString(R.string.address_book));
        binding.includeTop.llBack.setVisibility(View.VISIBLE);
        binding.includeSelect.recyclerViewContactsType.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewFollowStatus.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewContactsFrom.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewTag.setLayoutManager(new GridLayoutManager(context, 3));
        initDialog();
        initPopWindow();
        List<LabelModel> followStatusData = new ArrayList<>();
        followStatusData.add(new LabelModel(getString(R.string.not_follow), 10, false));
        followStatusData.add(new LabelModel(getString(R.string.following), 20, false));
        followStatusData.add(new LabelModel(getString(R.string.no_intention), 40, false));
        followStatusData.add(new LabelModel(getString(R.string.already_transform), 30, false));
        followStatusData.add(new LabelModel(getString(R.string.all), 50, false));
        followStatusAdapter = new LabelAdapter(2, context, followStatusData, this);
        binding.includeSelect.recyclerViewFollowStatus.setAdapter(followStatusAdapter);

        Bundle bundle = getIntent().getExtras();
        List<LabelModel> contactTypeData = (List<LabelModel>) bundle.getSerializable(Constant.listKey);
        boolean isHas = false;
        if (contactTypeData != null) {
            for (LabelModel labelModel : contactTypeData) {
                if (labelModel.getSort() == 1) {
                    labelModel.setSelect(true);
                    isHas = true;
                }
            }
            if (!isHas) {
                contactsType = contactTypeData.get(0).getSort();
            }
            contactsTypeAdapter = new LabelAdapter(1, context, contactTypeData, AddressBookActivity.this);
            binding.includeSelect.recyclerViewContactsType.setAdapter(contactsTypeAdapter);
        }

        // ---------------联系人来源-------------------
        viewModel.getContactSource();

        // ---------------联系人列表-------------------
        ContactsParamsModel contactsParamsModel = new ContactsParamsModel();
        showLoadingDialog();
        viewModel.getContactsList(1, contactsParamsModel);
        addressBookAdapter = new AddressBookAdapter(context, data);
        binding.recyclerView.setAdapter(addressBookAdapter);

        // ---------------联系人标签-------------------
        tagAdapter = new TagAdapter(context, tagsData, this);
        binding.includeSelect.recyclerViewTag.setAdapter(tagAdapter);
        viewModel.getTag();
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initClick() {
        binding.includeTop.ivSort.setOnClickListener(this);
        binding.includeTop.ivSelect.setOnClickListener(this);
        binding.includeTop.ivSearch.setOnClickListener(this);
        binding.includeTop.ivAddBusiness.setOnClickListener(this);
        binding.includeSelect.tvConfirm.setOnClickListener(this);
        binding.includeSelect.tvReset.setOnClickListener(this);
        viewModel.onDelayClick(binding.includeSelect.tvChoosePerson, o -> {
            if (isFirstRequest) {
                showLoadingDialog();
                viewModel.getTreeData("");
            } else {
                if (treeDialog != null) {
                    treeDialog.showDialog();
                }
            }
        });

        viewModel.onDelayClick(binding.includeSelect.ivDelete, o -> {
            chooseNode = null;
            orgId = null;
            binding.includeSelect.tvChoosePerson.setText("");
            binding.includeSelect.tvChoosePerson.setEnabled(true);
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            if (treeDialog != null) {
                treeDialog.reset();
            }
        });

        // 标签-更多
        binding.includeSelect.tvTagMore.setOnClickListener(v -> {
            Drawable drawable;
            if (binding.includeSelect.tvTagMore.getText().toString().equals(getString(R.string.more))) {
                binding.includeSelect.tvTagMore.setText(getString(R.string.no_expand));
                tagAdapter.setItemCount(tagsData.size());
                drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_up, null);
            } else {
                binding.includeSelect.tvTagMore.setText(getString(R.string.more));
                tagAdapter.setItemCount(9);
                drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_down, null);
            }
            binding.includeSelect.tvTagMore.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getContactsList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getContactsList(page);
            }
        });

        addressBookAdapter.setOnCallListener((telList, id, userName) -> {
            contactId = id;
            clientName = userName;
            if (telList.size() > 1) {
                initSinglePickerView(telList);
            } else if (telList.size() == 1) {
                mTelNumber = telList.get(0);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
            }
        });

        viewModel.onDelayClick(binding.includeTop.llBack, o -> finish());

        // ---------------组织架构-------------------
        viewModel.treeData.observe(this, treeBean -> {
            dismissLoadingDialog();
            isFirstRequest = false;
            Node node = treeBean.getData();
            if (null != node) {
                mData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                        node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                initList(node.getChildren());
                initList(node.getUserList());
                if (chooseNode != null) {
                    for (Node mNode : mData) {
                        if (mNode.getId().equals(chooseNode.getId())) {
                            mNode.setChecked(true);
                            break;
                        }
                    }
                }
            }
            treeDialog.refreshData(TextUtils.isEmpty(mKeyword) ? 1 : 10);
            if (!treeDialog.isShow()) {
                treeDialog.showDialog();
            }
            dismissLoadingDialog();
        });

        viewModel.mErrorData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
            binding.smartRefreshLayout.finishRefresh();
            binding.smartRefreshLayout.finishLoadMore();
        });

        viewModel.contactsData.observe(this, addressDataModel -> {
            binding.includeTop.tvBusinessCount.setText(contactsTypeName.substring(0, 2) + "· " + addressDataModel.getTotal());
            List<AddressDataModel.AddressModel> list = addressDataModel.getRecords();
            if (list.size() < Constant.pageSize) {
                binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
            }
            if (page == 1) {
                data = list;
                addressBookAdapter.onRefresh(list, contactsType);
                binding.smartRefreshLayout.finishRefresh();
            } else {
                addressBookAdapter.addData(list);
                binding.smartRefreshLayout.finishLoadMore();
            }
            dismissLoadingDialog();
        });

        viewModel.mErrorData.observe(this, s -> dismissLoadingDialog());

        viewModel.tagsData.observe(this, contactsTagModels -> {
            tagsData = contactsTagModels;
            tagAdapter.onRefresh(tagsData);
            if (null != contactsTagModels && !contactsTagModels.isEmpty()) {
                if (tagsData.size() > 9) {
                    binding.includeSelect.tvTagMore.setVisibility(View.VISIBLE);
                }
                binding.includeSelect.tvTagText.setVisibility(View.VISIBLE);
            } else {
                binding.includeSelect.tvTagText.setVisibility(View.GONE);
            }
        });

        viewModel.contactSourceData.observe(this, labelModels -> {
            contactsFromData = labelModels;
            contactsFromAdapter = new LabelAdapter(4, context, contactsFromData, AddressBookActivity.this);
            binding.includeSelect.recyclerViewContactsFrom.setAdapter(contactsFromAdapter);
        });
    }

    private void initList(List<Node> list) {
        if (list == null || list.isEmpty())
            return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            mData.add(new Node(node.getName(), node.getId(), node.getParentId(),
                    node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
            if (node.getChildren() == null || node.getChildren().isEmpty()) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }

    private void initSinglePickerView(List<String> data) {
        SinglePickerView singlePickerView = new SinglePickerView(this, getString(R.string.call_num), data) {
            @Override
            public void confirm(String label, int position) {
                mTelNumber = label;
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
            }
        };
        singlePickerView.showSinglePickerView();
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                RequestUtils.callNum(context, mTelNumber);
                RequestUtils.addContactsFollow(contactId, clientName, mTelNumber);
                Constant.pushBusinessId = "1";
            }

            @Override
            public void rightClick() {
                RequestUtils.callbackOutbound2(context, mTelNumber, contactId, clientName);
            }
        };

        treeDialog = new TreeDialog(AddressBookActivity.this, mData) {
            @Override
            public void confirm(Node node) {
                chooseNode = node;
                binding.includeSelect.tvChoosePerson.setText(node.isChecked() ? node.getName() : "");
                orgId = node.isChecked() ? node.getOrgId() : null;
                binding.includeSelect.tvChoosePerson.setEnabled(!node.isChecked());
                binding.includeSelect.ivDelete.setVisibility(node.isChecked() ? View.VISIBLE : View.GONE);
            }

            @Override
            public void search(String keyword, Node node) {
                showLoadingDialog();
                mKeyword = keyword;
                viewModel.getTreeData(keyword);
            }
        };
        treeDialog.setTitle(getString(R.string.please_choose_create_person));
    }

    private void initPopWindow() {
        popupWindow = new SortPopupWindow(context, false) {
            @Override
            public void confirm(String mSortType, String mOrderKey) {
                sortType = mSortType;
                orderKey = mOrderKey;
                page = 1;
                getContactsList(page);
            }
        };
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_sort) {
            binding.includeTop.ivSort.setOnClickListener(v -> popupWindow.showPopupWindow(binding.includeTop.line));
        } else if (id == R.id.iv_select) {
            binding.drawerLayout.openDrawer(GravityCompat.END);
        } else if (id == R.id.iv_search) {
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.typeKey, contactsType);
            JumpIntent.jump(AddressBookActivity.this, SearchAddressBookActivity.class, bundle);
        } else if (id == R.id.iv_add_business) {
            UMengUtil.setCountEventId(Constant.ADD_CONTACTS);
            Bundle bundle2 = new Bundle();
            bundle2.putInt(Constant.flagKey, 0);
            JumpIntent.jump(AddressBookActivity.this, AddContactsActivity.class, bundle2);
        } else if (id == R.id.tv_confirm) {
            binding.drawerLayout.closeDrawers();
            page = 1;
            binding.recyclerView.scrollToPosition(0);
            binding.smartRefreshLayout.autoRefresh();
        } else if (id == R.id.tv_reset) {
            followStatusAdapter.resetData(2);
            contactsFromAdapter.resetData(3);
            binding.includeSelect.llCreatePerson.setVisibility(View.GONE);
            orgId = null;
            binding.includeSelect.tvChoosePerson.setText("");
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            contactsTypeName = getString(R.string.my_contacts);
            contactsType = 1;
            binding.includeSelect.tvChoosePerson.setEnabled(true);
            tagAdapter.resetData();
            followStatus = null;
            tagStrData.clear();
            contactsTypeAdapter.resetData(1);
            contactsFrom = null;
            chooseNode = null;
            if (treeDialog != null) {
                treeDialog.reset();
            }
            binding.includeSelect.llTag.setVisibility(View.VISIBLE);
        }
    }

    private void getContactsList(int page) {
        ContactsParamsModel contactsParamsModel = new ContactsParamsModel();
        contactsParamsModel.setExamine(contactsType); // 1-我的联系人 2-部门联系人3-全部联系人
        contactsParamsModel.setContactSourceId(contactsFrom); // 联系人来源：0 手动录入，1 企业收藏
        contactsParamsModel.setFollowStatus(followStatus); // 跟进状态：10 未跟进、20正在跟进、30已转化、40无意向、50全部
        if (contactsType != 1) {
            if (chooseNode != null && chooseNode.getIsDept() == 1) {
                contactsParamsModel.setCreatsignDeptId(orgId);
            } else {
                contactsParamsModel.setCreatSignId(orgId); // 创建人id
            }
        } else {
            contactsParamsModel.setLabelNames(tagStrData); // 标签
        }
        contactsParamsModel.setOrderKey(orderKey); // 排序key，chanceWeight、createTime、lastFollowTime
        contactsParamsModel.setOrderType(sortType); // 升序asc，降序desc
        viewModel.getContactsList(page, contactsParamsModel);
    }

    @Override
    public void onLabelItemClickListener(int flag, LabelModel model) {
        switch (flag) {
            case 1:
                contactsTypeName = model.getName();
                contactsType = model.getSort();
                binding.includeSelect.llCreatePerson.setVisibility(contactsType == 1 ? View.GONE : View.VISIBLE);
                binding.includeSelect.llTag.setVisibility(contactsType == 1 ? View.VISIBLE : View.GONE);
                break;
            case 2:
                followStatus = model.isSelect() ? model.getNum() : null;
                break;
            case 4:
                contactsFrom = model.isSelect() ? model.getId() : null;
                break;
        }
    }

    @Override
    public void onTagItemClickListener(ContactsTagModel model) {
        tagStrData.clear();
        for (ContactsTagModel contactsTagModel : tagsData) {
            if (contactsTagModel.isSelect()) {
                tagStrData.add(contactsTagModel.getLabelName());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshContactsList)) {
                page = 1;
                getContactsList(page);
                viewModel.getTag();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}